package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;
import drds.plus.sql_process.type.impl.IntervalType;

import java.util.Calendar;

/**
 * ADDDATE(date,interval_primary expression_list unit), ADDDATE(expression_list,days) When invoked with the
 * interval_primary form of the second argument, ADDDATE() is a synonym for DATE_ADD().
 * The related function SUBDATE() is a synonym for DATE_SUB(). For information
 * on the interval_primary unit argument, see the discussion for DATE_ADD().
 *
 * <pre>
 * mysql> SELECT DATE_ADD('2008-01-02', interval_primary 31 DAY);
 *         -> '2008-02-02'
 * mysql> SELECT ADDDATE('2008-01-02', interval_primary 31 DAY);
 *         -> '2008-02-02'
 * </pre>
 * <readPriority>
 * When invoked with the days form of the second argument, MySQL treats it setAliasAndSetNeedBuild
 * an integer number of days to be added to expression_list.
 *
 * <pre>
 * mysql> SELECT ADDDATE('2008-01-02', 31);
 *         -> '2008-02-02'
 * </pre>
 */
public class DateAdd extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Timestamp timestamp = Type.TimestampType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.setTime(timestamp);

        Object day = args[1];
        if (day instanceof IntervalType) {
            ((IntervalType) day).process(cal, 1);
        } else {
            cal.add(Calendar.DAY_OF_YEAR, Type.IntegerType.convert(day));
        }

        Type type = getReturnType();
        return type.convert(cal);
    }

    public Type getReturnType() {
        Type type = getFirstArgType();
        return type;
    }

    public String[] getFunctionNames() {
        return new String[]{"DATE_ADD", "ADDDATE"};
    }
}
